package util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

//数据库工具类
public class C3P0Util {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //静态代码块只能执行一次
    private static ComboPooledDataSource ds;
    static {
        InputStream is = C3P0Util.class.getClassLoader().getResourceAsStream("db.properties");
        //创建一个properties对象
        Properties properties = new Properties();
        try {
            //properties
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            ds=new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setUser(username);
            ds.setJdbcUrl(url);
            ds.setPassword(password);
            //设置初始连接池的数量
            ds.setInitialPoolSize(5);
            //设置最大连接数
            ds.setMaxPoolSize(10);
            //设置最小连接数
            ds.setMinPoolSize(3);
            //设置使用完后自动获取连接的数量
            ds.setAcquireIncrement(3);
            //设置两次连接的间隔
            ds.setAcquireRetryAttempts(500);

        } catch (IOException | PropertyVetoException e) {
            e.printStackTrace();
        }
    }
    static {
        try {
            //加载驱动类
            Class.forName("oracle.jdbc.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //创建连接
    public static Connection getConnection() throws ClassNotFoundException, SQLException {


        //创建连接

        return ds.getConnection();
    }

    //关闭资源
    public static void close(AutoCloseable...closeables){
        for (AutoCloseable closeable : closeables) {
            if (closeable!=null){
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
